package com.sebiotec.book.ui.fragment;

import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.RequiresApi;
import androidx.cardview.widget.CardView;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.allen.library.RxHttpUtils;
import com.sebiotec.basecommon.utils.base.BaseLazyLoadingFragment;
import com.sebiotec.basecommon.utils.tools.SoftKeyBoardListener;
import com.sebiotec.book.R;
import com.sebiotec.book.R2;
import com.sebiotec.book.adapt.PendingAdapt;
import com.sebiotec.book.model.SearchEntrty;
import com.sebiotec.book.model.event.DateEvent;
import com.sebiotec.book.model.event.RefEvent;
import com.sebiotec.book.viewmodel.PendingVIewModel;
import com.loonggg.weekcalendar.view.WeekCalendar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.statelayout.MultipleStatusView;
import com.xw.repo.XEditText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PendingFragment extends BaseLazyLoadingFragment {
    @BindView(R2.id.week_calendar)
    WeekCalendar weekCalendar;
    @BindView(R2.id.iv_date)
    ImageView ivDate;
    @BindView(R2.id.recy_pending)
    RecyclerView recyPending;
    @BindView(R2.id.ed_seach)
    XEditText edSeach;
    @BindView(R2.id.rl_pending)
    RelativeLayout rlPending;
    @BindView(R2.id.iv_search)
    ImageView ivSearch;
    @BindView(R2.id.card)
    CardView card;
    @BindView(R2.id.multiple_pending_status_view)
    MultipleStatusView multipleStatusView;
    private boolean isShow = false;
    private PendingVIewModel mPendingVIewModel;
    private PendingAdapt upComingAdapt;
    @BindView(R2.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private String mSearch;
    private String date;
    private  int PageSize=30;
    private  int PageIndex=1;
    private MiniLoadingDialog dialog;

    @Override
    protected String getLogTag() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_pending;
    }

    @Override
    protected void initView(View root) {
        EventBus.getDefault().register(this);
        mPendingVIewModel = ViewModelProviders.of(this).get(PendingVIewModel.class);
//        aCache = ACache.get(getActivity(),ETFConstant.APPHOMEPATH);
        InitUI();
    }

    @Override
    protected void onFragmentResume() {
        super.onFragmentResume();
        if (dialog!=null){
            dialog.show();
        }else{
            dialog=new MiniLoadingDialog(getActivity(),getString(R.string.tip_loading_message));
            dialog.show();
        }
        mSearch = "";
        edSeach.setTextEx("");
        date="";
        PageIndex=1;
        refreshLayout.setNoMoreData(false);
        EventBus.getDefault().post(new RefEvent(true,date,mSearch,-1));
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault ().removeAllStickyEvents ();
        EventBus.getDefault().unregister(this);
        if (dialog!=null){
            dialog.dismiss();
            dialog=null;
        }
        RxHttpUtils.cancel("Pending");
    }
    @Override
    public void onResume() {
        super.onResume();

    }
    private void InitUI() {
//        try {
//            TextView tv=null;
//            tv.setText("123");
//        }catch (Exception e){
//            CrashReport.postCatchedException(e);
//        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyPending.setLayoutManager(linearLayoutManager);
        edSeach.setOnXFocusChangeListener(new XEditText.OnXFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    rlPending.setBackground(getActivity().getDrawable(R.drawable.ll_shape_ed));
                } else {
                    // 此处为失去焦点时的处理内容
                    rlPending.setBackground(getActivity().getDrawable(R.drawable.ll_shape));
                }
            }
        });
        edSeach .addTextChangedListener(textWatcher);

        edSeach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                edSeach.setFocusable(true);
                edSeach.setFocusableInTouchMode(true);
                edSeach.requestFocus();
            }
        });
        SoftKeyBoardListener.setListener(getActivity(), new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {

            }

            @Override
            public void keyBoardHide(int height) {
                edSeach.setFocusable(false);
            }
        });

        weekCalendar.setOnDateClickListener(new WeekCalendar.OnDateClickListener() {
            @Override
            public void onDateClick(String time) {
                date=time;
                PageIndex=1;
                EventBus.getDefault().post(new RefEvent(true,date,mSearch));
                EventBus.getDefault().postSticky(new DateEvent(true,date,mSearch,2));
                multipleStatusView.showLoading();
                refreshLayout.setNoMoreData(false);
                getFristData();
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {

                EventBus.getDefault().post(new RefEvent(true,date,mSearch));
                refreshlayout.setEnableLoadMore(true);
                PageIndex=1;
                mPendingVIewModel.getUpComingData(1, mSearch, PageIndex, PageSize,date, new PendingVIewModel.MyDataCallBack<Object>() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onDataSuccessCallBack(Object o) {

                        refreshlayout.finishRefresh();//传入false表示刷新失败
                        PageIndex++;
                        SearchEntrty rowsBeans = (SearchEntrty) o;
                        if (rowsBeans.getRows() == null || rowsBeans.getRows().size() == 0) {
                            multipleStatusView.showEmpty();
                        } else {

                            List<SearchEntrty.RowsBean> rows = rowsBeans.getRows();
//                            rows.sort((SearchEntrty.RowsBean m1, SearchEntrty.RowsBean m2) -> m2.getPickupDateTime().compareTo(m1.getPickupDateTime()));

                            if (upComingAdapt!=null){
                                upComingAdapt.setNewData(rows);
                                recyPending.setAdapter(upComingAdapt);
                            }else{
                                upComingAdapt = new PendingAdapt(R.layout.item_upcoming,rows);
                                recyPending.setAdapter(upComingAdapt);
                            }

                        }

                    }

                    @Override
                    public void onDataFailCallBack(Object o) {

                        refreshlayout.finishRefresh(false);//传入false表示刷新失败
                    }


                });


            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(final RefreshLayout refreshlayout) {

                mPendingVIewModel.getUpComingData(1, mSearch,PageIndex, PageSize,date, new PendingVIewModel.MyDataCallBack<Object>() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onDataSuccessCallBack(Object o) {
                        SearchEntrty rowsBeans = (SearchEntrty) o;
                        if (rowsBeans.getRows() == null || rowsBeans.getRows().size() == 0) {

                            refreshlayout.setNoMoreData(true);

                        } else {
                            PageIndex++;
                            List<SearchEntrty.RowsBean> rows = rowsBeans.getRows();
//                            rows.sort((SearchEntrty.RowsBean m1, SearchEntrty.RowsBean m2) -> m2.getPickupDateTime().compareTo(m1.getPickupDateTime()));

                            refreshlayout.finishLoadMore();
                            upComingAdapt.addData(rows);



                        }

                    }

                    @Override
                    public void onDataFailCallBack(Object o) {
                        refreshlayout.finishLoadMore(false/*,false*/);//传入false表示加载失败

                    }


                });




            }
        });


    }
    public void getFristData() {
        mPendingVIewModel.getUpComingData(1, mSearch, PageIndex, PageSize,date, new PendingVIewModel.MyDataCallBack<Object>() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onDataSuccessCallBack(Object o) {
                SearchEntrty rowsBeans = (SearchEntrty) o;

                if (dialog!=null){
                    dialog.dismiss();
                }

                if (rowsBeans.getRows() == null || rowsBeans.getRows().size() == 0) {
                    multipleStatusView.showEmpty();
                } else {
                        PageIndex++;
                    List<SearchEntrty.RowsBean> rows = rowsBeans.getRows();
//                    rows.sort((SearchEntrty.RowsBean m1, SearchEntrty.RowsBean m2) -> m2.getPickupDateTime().compareTo(m1.getPickupDateTime()));
                    multipleStatusView.showContent();
                    if (upComingAdapt!=null){



                        upComingAdapt.setNewData(rows);
                        recyPending.setAdapter(upComingAdapt);
                    }else{
                        upComingAdapt = new PendingAdapt(R.layout.item_upcoming, rows);
                        recyPending.setAdapter(upComingAdapt);
                    }

                }

            }

            @Override
            public void onDataFailCallBack(Object o) {
                if (dialog!=null){
                    dialog.dismiss();
                }
                if (multipleStatusView!=null){
                    multipleStatusView.showError();
                }


            }


        });

    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
               mSearch=edSeach.getText().toString();
        }
    };
    public void initData() {

        getFristData();
        multipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multipleStatusView.showLoading();
                PageIndex=1;
                refreshLayout.setNoMoreData(false);
                getFristData();
            }
        });


    }

    @OnClick({R2.id.iv_search, R2.id.iv_date})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.iv_search) {

            multipleStatusView.showLoading();
            PageIndex=1;
            refreshLayout.setNoMoreData(false);

            mSearch= edSeach.getTextEx().toString().trim();
            getFristData();
        } else if (id == R.id.iv_date) {
            if (isShow) {
                card.setVisibility(View.GONE);
                isShow = false;
                multipleStatusView.showLoading();
                date="";
                PageIndex=1;
                refreshLayout.setNoMoreData(false);

                getFristData();
            } else {
                card.setVisibility(View.VISIBLE);
                isShow = true;
            }
        }
    }





    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void retf(DateEvent event){
        if (event.getIsBookmark()!=2){
            date=event.getDate();
            weekCalendar.setSeleceDate(date);
//            initData();
        }





    }

}
